import './presetVar'
import requestApi from "src/erm/sscrppublic/common/components/requestApi";
import {ajax, toast ,pageTo} from 'nc-lightapp-front';
import { getRequest1 } from './initTemplate'
import presetVar from "../../adjustment/card/presetVar";
import { forEach, get } from 'lodash-es'
import attachments from 'uap/common/components/getAttachmentInfo';
const { getAttachments, getAttachmentsInfo } = attachments;

let requestDomain =  '';
let referResultFilterCondition='';
let requestApiOverwrite = {
    ...requestApi,
    //单据模板接口
    tpl: (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/loanmanage/LoanmanageTempletAction.do`,
            data: opt.data,
            success: opt.success
        });
    },
    loaddata:(opt) => {
       let props = opt.props;
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/loanmanage/LoanmanageDefDataAction.do?tradetype=${window.presetVar.tradetype}&uistatus=add`,
            data: opt.data,
            success: (data) => {
                const arr = _.get(data,'data.bodys.jk_busitem.rows',[])
                setAlreadySelected(arr)
                // data = data.data;
                // let newData = {}
                // newData.head = data.data.head.head;
                // newData.body = data.data.bodys[0].body;
                //referResultFilterCondition = JSON.parse(JSON.parse(data.data.userjson).crossrule);//交叉校验规则设置
                window.presetVar.reimsrc = JSON.parse(JSON.parse(data.data.userjson).reimsrc);//核心控制项-影响因素
                window.presetVar.showitemkey = JSON.parse(data.data.userjson).showitemkey;//显示项
                window.presetVar.reimruleitemkeys = JSON.parse(data.data.userjson).reimruleitemkeys;//报销标准涉及字段
                window.presetVar.ratecontorl = JSON.parse(data.data.userjson).RATECONTORL//集团参数NC004“组织汇率是否可编辑
                window.presetVar.zzbwb = JSON.parse(data.data.userjson).ZZBWB//组织币种
                let headValues = data.data.head['head'].rows[0].values;
                console.log('借款单查询===',data)
                window.presetVar.reloadHead = data.data.head['head']
                const djlx =  JSON.parse(data.data.userjson)
                if(djlx && djlx.IS_MACTRL){//是否冲借款
                    window.presetVar["IS_MACTRL"]=djlx.IS_MACTRL;
                }
                if(djlx && djlx.noAmountSq){//是否无金额
                    window.presetVar.noAmountSq = djlx.noAmountSq
                }
                data.data.head['head'].rows.forEach((row) => {
                    for (let attrCode in row.values) {
                        let initialvalue = {
                            value : row.values[attrCode].value,
                            display: row.values[attrCode].display,
                            scale: row.values[attrCode].scale
                        };
                        opt.meta['head'].items.forEach((item) => {
                            if (item.attrcode == attrCode && attrCode.indexOf('.')<0) {
                                item.initialvalue = initialvalue;
                               // if(item.itemtype == 'refer' ||item.attrcode=='paytarget'){
                                //    item.visible = true;//zheli fangkai
                                //    item.disabled = false;
                                //     if(item.attrcode =="pk_org_v"){
                                //         item.visible = false;
                                 //    }
                                //}
                                if(item.itemtype == 'refer'){
                        
                                    //处理交叉校验规则和参照过滤
                                    filterAllRefParm(item,props, 'head');
                                }
                            }
                        });

                        //适配多表头
                        if (opt.meta.formrelation) {
                            opt.meta.formrelation[presetVar.head.head1].forEach((item) => {
                                if (opt.meta[item]) {
                                    opt.meta[item].items.forEach((key) => {
                                        if (key.attrcode == attrCode && attrCode.indexOf('.')<0) {
                                            key.initialvalue = initialvalue;

                                            if(key.itemtype == 'refer'){

                                                //处理交叉校验规则和参照过滤
                                                filterAllRefParm(key,props, presetVar.head.head1);
                                            }
                                        }
                                    })
                                }

                            });
                        }
                    }
                });
                let numberInitialvalueField = ['bbhl','tax_rate','groupbbhl','globalbbhl','rowno'];
                for(let body in data.data.bodys){
                    if(data.data.bodys[body] && data.data.bodys[body].rows){
                        data.data.bodys[body].rows.forEach((row) => {
                            for (let attrCode in row.values){
                                let initialvalue = {
                                    value: row.values[attrCode].value,
                                    display: row.values[attrCode].display,
                                    scale: row.values[attrCode].scale
                                };
                                // for (let table in opt.meta.gridrelation) {
                                    opt.meta[body].items.forEach((item) => {
                                        if(item.attrcode=='tablecode'){
                                            let itvalue = {
                                                value:body,
                                                display:body
                                            }
                                            item.initialvalue = itvalue;
                                        }
                                        
                                      // if(item.itemtype == 'refer'){
                                          // item.visible = true;//zheli fangkai
                                          // item.disabled = false;
                                        //}
                                        if (item.attrcode == attrCode && attrCode.indexOf('.')<0){
                                            //金额类字段不需要设默认值
                                            if(item.itemtype != 'number' || numberInitialvalueField.indexOf(item.attrcode) >= 0){
                                                item.initialvalue = initialvalue;
                                            } else{
                                                item.initialvalue = {
                                                    // TOP 金额字段不需要显示默认值 chengwebc DEL
                                                    scale: row.values[attrCode].scale
                                                };
                                            }
                                        }
                                        if(item.itemtype == 'refer' && item.visible == true){
                                            //处理交叉校验规则和参照过滤
                                            filterAllRefParm(item,props, body);
                                        }
                                    });

                                    //处理侧拉
                                    if(opt.meta[body+"&childform2"]&&opt.meta[body+"&childform2"].items){
                                        opt.meta[body+"&childform2"].items.forEach((item) => {
                                            if(item.attrcode=='tablecode'){
                                                let itvalue = {
                                                    value:body,
                                                    display:body
                                                }
                                                item.initialvalue = itvalue;
                                            }
                                            
                                          // if(item.itemtype == 'refer'){
                                              // item.visible = true;//zheli fangkai
                                              // item.disabled = false;
                                            //}
                                            if (item.attrcode == attrCode && attrCode.indexOf('.')<0){
                                                //金额类字段不需要设默认值
                                                if(item.itemtype != 'number' || numberInitialvalueField.indexOf(item.attrcode) >= 0){
                                                    item.initialvalue = initialvalue;
                                                } else{
                                                    item.initialvalue = {
                                                        // TOP 金额字段不需要显示默认值 chengwebc DEL
                                                        scale: row.values[attrCode].scale
                                                    };
                                                }
                                            }
                                            if(item.itemtype == 'refer' && item.visible == true){
                                                //处理交叉校验规则和参照过滤
                                                filterAllRefParm(item,props, body);
                                            }
                                          
                                        });
                                    }
                                    
                                }
                            // }
                        });
                    }
                }
                opt.success(data.data);
            }
        })
    },
    //暂存
    saveTempjkbx:(opt) => {
        ajax({
            url:opt.url || `${requestDomain}/nccloud/erm/loanmanage/LoanmanageTempSaveAction.do`,
            data: opt.data,
            success: (data) =>{
                data = data.data;
                if(data.success=='false'){
                    let toastType = 'danger'
                    toast({content:data.message || '未知错误',color:toastType})
                    return;
                }
                opt.success(data)
            },
            error:(data)=>{
                toast({content:data.message,color:'danger'});
            }
        })
    }, 

    relateLoanInvoice:(opt)=>{
        ajax({
            url: opt.url ||`${requestDomain}/nccloud/erm/loanmanage/LoanmanageRelaSqAction.do?uistatus=add&tradetype=`+window.presetVar.tradetype,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            }
        })
    },
    savejkbx:(opt) => {

        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/loanmanage/LoanmanageSaveAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error:(data)=>{
                toast({ content: data.message, color: 'danger' });
                // alert(data.message);
            }
        })
    },
     //判断客户和供应商是否是散户接口
   isFreecust:(opt)=>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/QueryIsFreeCustAction.do`,
            data:opt.data,
            success: (response) => {
                const data = response.data
                if (response.success) {
                    opt.success(data);
                } else {
                    toast({content:data.message,color:'danger'});
                }
            }
        })
    },
    valueChange:(opt) => {

        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/loanmanage/LoanmanageValueChangeAction.do`,
            data: opt.data,
            async:false,
            success: (data) => {
                //referResultFilterCondition = JSON.parse(JSON.parse(data.data.userjson).crossrule);//交叉校验规则设置
                data = data.data;
                opt.success(data);
            }
        })
    },
    viewBill:(opt) =>{
        const props = opt.props;
        const meta = props.meta.getMeta()
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/loanmanage/LoanmanageViewAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                console.log('借款单查询===',data)
                window.presetVar.reloadHead = data.head['head']
                const userjson_parse = JSON.parse(data.userjson) || {}
                console.log('userjson_parse===',userjson_parse)
                //存当前的是否无金额申请勾选
                window.presetVar.noAmountSq = userjson_parse.noAmountSq
                window.presetVar["IS_MACTRL"]=userjson_parse.IS_MACTRL;
                const arr = _.get(data,'bodys.jk_busitem.rows',[])
                setAlreadySelected(arr)
                if (meta.head) {
                    meta.head.items.forEach((item) => {
                        if (item.itemtype == 'refer') {
                            //处理交叉校验规则和参照过滤
                            filterAllRefParm(item, props, 'head');
                        }
                    });
                }

                //适配多表头
                if (meta.formrelation && meta.formrelation[presetVar.head.head1]) {
                    meta.formrelation[presetVar.head.head1].forEach((item) => {
                        if (meta[item]) {
                            meta[item].items.forEach((key) => {
                                if (key.itemtype == 'refer') {
                                    //处理交叉校验规则和参照过滤
                                    filterAllRefParm(key, props, presetVar.head.head1);
                                }
                            });
                        }
                    });
                }
                props.meta.addMeta(meta);
                forEach(data.head, (item, key) => {
                    props.form.setFormItemsValue(key, get(data, 'head.head.rows[0].values', {}));
                })
                forEach(data.bodys, (item, key) => {
                    props.cardTable.setTableData(key, item)
                })
                opt.success(data);
            }
        });
    },
    copyBill:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/loanmanage/LoanmanageCopyAction.do`,
            data: opt.data,
            success: (data) => {
                  data = data.data;
                opt.success(data);
            }
        });
    },
    submitBill:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/loanmanage/LoanmanageSubmitAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                if(data.success!=undefined&&data.success=='false'){
                    toast({content:data.message,color:'warning'});
                    return;
                }
                opt.success(data);
            },
            error:(data) =>{
                toast({ content: data.message, color: 'danger' });
                // alert(data.message);
            }
        });
    },
    billRemove:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/loanmanage/LoanmanageDeleteAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            }
        });
    },

    billInvalid:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/loanmanage/LoanmanageInvalidAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'warning'});
            }
        });
    },
    generatBillId:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/action/generatBillId.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error:(data) =>{
                toast({ content: data.message, color: 'danger' });
            }
        });
    },
    queryextend:(opt)=>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountExtendAttrAction.do`,
            data: opt.data,
            async:false,
            success: (data) => {
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'warning'});
            }
        });
    },
    billRecall:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/loanmanage/LoanmanageRecallAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error:(data) =>{
                toast({ content: data.message, color: 'danger' });
            }
        });
    },
    getUnEditAttributes:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/pub/ErmAttributeEditableAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'warning'});
            }
        });
    },
    handleLoadDataResDada:(meta,data,props) =>{
       handleLoadDataResDada(meta, data,props)
    },
    filterAllRefParm:(item,props, flag) =>{
        filterAllRefParm(item,props, flag)
    },
    filterDatas:(data) =>{
        return filterDatas(data)
    },
    linkJkbx : (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/expenseaccountLinkQueryAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'error'});
            }
        });
    },
    makebill: (opt) => {
        let srcAppcode ='201102CBSP';
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/makebill/MakeBillJKBXAction.do`,
            data: opt.data,
            success: (res) => {
                console.log('接口返回数据：', res);
                let { data } = res;
                if (!data) {
                    return;
                }
                //let srccode = srcAppcode + '_MadeBill2019';
                //cacheTools.set(srcAppcode + '_MadeBill2019',data.pklist);
                //let srccode = srcAppcode + res.data.cachekey;
               // cacheTools.set(srcAppcode + res.data.cachekey, data.pklist);

                


                opt.success(data);
            },
            error: (data) => {
                toast({ content: data.message, color: 'danger' });
            }
        })
    },
    /**
    * 获取控制附件修改和必须上传的接口
    */
   getAttachmentControlParams: (opt) => {
    ajax({
        url: opt.url || `${requestDomain}/nccloud/erm/ermextendattr/ErmAccessoryControl.do`,
        data: opt.data,
        success: (response) => {
            const data = response.data
            if (data && data.success) {
                opt.success(data);                    
            } else {
                toast({content:data.message,color:'danger'});
            }
        },
        error:(data)=>{
            toast({content:data.message,color:'danger'});
        }
    })
},

/**
* 判断附件是否已经上传
*/
isAttachmentsUploaded: async (billId) => {
    const count = await getAttachments(billId)
    return count > 0
}

}
export function setAlreadySelected(data){
    //window.presetVar.applicationForm_table
    let alreadySelecteds = {
        head:{
            head:[],body:{}
        }
    }
    //pk_mtapp_detail.value
    data.forEach(item=>{
        const pk_head_index = alreadySelecteds.head.head.findIndex(item1=>item1===item.values.pk_item.value)
        if(pk_head_index<0){
            alreadySelecteds.head.head.push(item.values.pk_item.value)
            alreadySelecteds.head.body[item.values.pk_item.value] = []
        }
        const pk_body_index = alreadySelecteds.head.body[item.values.pk_item.value].findIndex(item1=>item1===item.values.pk_mtapp_detail.value)
        if(pk_body_index<0){
            alreadySelecteds.head.body[item.values.pk_item.value].push(item.values.pk_mtapp_detail.value)
        }
    })
    window.presetVar.applicationForm_table = alreadySelecteds
}
async function isUploadedAttachments(props, multiLang) {
    const billId = props.getUrlParam('billid') || props.getUrlParam('id') || this.state.billId || "";
    if (props.getUrlParam('isinit') === true) {
        //借款期初不校验附件
        return true
    }
    //附件控制必传
    if (window.presetVar.attachmentControl && window.presetVar.attachmentControl.necessary) {
        if (!billId) {
            // 必须上传附件
            toast({content: multiLang && multiLang.get('201107TZD-0004'),color:'danger'})
            return false
        }
        const hasUploaded = await requestApiOverwrite.isAttachmentsUploaded(billId)
        if (hasUploaded) {
            return true
        } else {
            // 必须上传附件
            toast({content: multiLang && multiLang.get('201107TZD-0004'),color:'danger'})
            return false
        }
    }
    return true
}

export {
    isUploadedAttachments
}

function handleLoadDataResDada(meta, data,props) {
    if(data.data.head['head'].rows[0])
    {
        let headValues = data.data.head['head'].rows[0].values;
        for (let attrcode in headValues) {
            meta['head'].items.forEach((item) => {
                if (item.attrcode == attrcode) {
                    item.initialvalue = {
                        value: headValues[attrcode].value,
                        display: headValues[attrcode].display=null?headValues[attrcode].value:headValues[attrcode].display
                    };

                    //处理交叉校验规则和参照过滤
                    // filterAllRefParm(item,headValues,headValues,props,'head');
                }

            });
        }
    }

    //适配多表头
    if (meta.formrelation) {
        let headValues = data.data.head['head'].rows[0].values;
        meta.formrelation[presetVar.head.head1].forEach((item) => {
            if (meta[item]) {
                meta[item].items.forEach((key) => {
                    let attrcode = key.attrcode;
                    if (headValues[attrcode]) {
                        key.initialvalue = {
                            value: headValues[attrcode].value,
                            display: headValues[attrcode].display=null?headValues[attrcode].value:headValues[attrcode].display
                        };

                        //处理交叉校验规则和参照过滤
                        // filterAllRefParm(key,headValues,headValues,props,'head');
                    }
                })
            }

        });
    }

    Object.keys(presetVar.body).forEach((bodyindex) =>{
        let bodyname = presetVar.body[bodyindex];
        if(data.data.bodys[bodyname] && data.data.bodys[bodyname].rows){
            data.data.bodys[bodyname].rows.forEach((row) => {
                let bodyValues = row.values;
                for (let attrcode in bodyValues) {
                    meta[bodyname].items.forEach((item) => {
                        if (item.attrcode == attrcode) {
                            item.initialvalue = {
                                value: bodyValues[attrcode].value,
                                display: bodyValues[attrcode].display = null ? bodyValues[attrcode].value : bodyValues[attrcode].display
                            };

        
                            //处理交叉校验规则和参照过滤
                            // let headValues = data.data.head['head'].rows[0].values;
                            // filterAllRefParm(item, bodyValues, headValues);
                        }

                    });
                }
            });
        }
    });
}
function filterAllRefParm(item, props, moudleid){
    let PublicDefaultRefFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder';//公共 
    let BusinessUnitTreeRefFilterPath ='nccloud.web.erm.action.ref.sqlbuilder.BusinessUnitTreeRefSqlBuilder';//组织
    let OrgTreeRefFilterPath ='nccloud.web.erm.action.ref.sqlbuilder.OrgTreeRefSqlBuilder';//组织
    let DeptClassTreeGridRef ='nccloud.web.erm.action.ref.sqlbuilder.DeptClassTreeGridRef';//部门
    let DeptTreeGridRef ='nccloud.web.erm.action.ref.sqlbuilder.DeptTreeGridRef';//部门
    let CurrtypeRefSqlFilterPath ='nccloud.web.erm.action.ref.sqlbuilder.CurrtypeRefSqlBuilder';//币种
    let PsndocClassFilterPath ='nccloud.web.erm.action.ref.sqlbuilder.PsndocClassTreeGridRef';//人员
    let PsndocTreeFilterPath ='nccloud.web.erm.action.ref.sqlbuilder.PsndocTreeGridRef';//人员
    let PsnbankaccRefSqlBuilder ='nccloud.web.erm.action.ref.sqlbuilder.PsnbankaccRefSqlBuilder';//个人银行账户
    let PsnbankaccTreeGridRef ='nccloud.web.erm.action.ref.sqlbuilder.PsnbankaccTreeGridRef';//个人银行账户
    let BankacctreeGridRef ='nccloud.web.erm.action.ref.sqlbuilder.BankacctreeGridRef';//个人银行账户
    let SupplierTreeGridRef ='nccloud.web.erm.action.ref.sqlbuilder.SupplierTreeGridRef';//供应商
    let ProjecTreetGridRef ='nccloud.web.erm.action.ref.sqlbuilder.ProjecTreetGridRef' ;//项目
    let CustomerTreeGridRef='nccloud.web.erm.action.ref.sqlbuilder.CustomerTreeGridRef';//客户
	let PublicDefaultGridRef='nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder';//公共
    const CustomerVersionTreeGridRef = 'nccloud.web.erm.action.ref.sqlbuilder.CustomerVersionTreeGridRef'
    const SupplierVersionGridRef =  'nccloud.web.erm.action.ref.sqlbuilder.SupplierVersionTreeGridRef'

   //所属组织，待确定是否需要特殊处理
    if (item.attrcode == 'pk_org') {
        item.queryCondition = () => {
            let paramurl = getRequest1(parent.window.location.hash);
            //如果没取到应用编码再取一下外层
            if(!paramurl.c){
                paramurl = getRequest1(parent.parent.window.location.hash);
            }
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['pk_group'].value))
            return {pk_group: data, TreeRefActionExt:OrgTreeRefFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y', appcode : paramurl.c}; // 根据pk_group过滤
        };
    }
    else if (item.attrcode == 'pk_org_v') {
        item.queryCondition = () => {
            let paramurl = getRequest1(parent.window.location.hash);
            //如果没取到应用编码再取一下外层
            if(!paramurl.c){
                paramurl = getRequest1(parent.parent.window.location.hash);
            }
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value
            return {pk_group: data, TreeRefActionExt:OrgTreeRefFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y', appcode : paramurl.c, isVerison : "Y"}; // 根据pk_group过滤
        };
    }

    if(item.attrcode === 'deptid'|| item.attrcode === 'deptid_v' || item.attrcode === 'center_dept'){
        //部门
        // item.refcode='uapbd/refer/org/DeptTreeRef/index'
        item.queryCondition = ()=>{
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['dwbm'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['dwbm'].value))
            
            return {pk_org: data,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y',TreeRefActionExt:DeptTreeGridRef,GridRefActionExt:DeptTreeGridRef}; // 根据apply_org过滤
        }
    }
    if(item.attrcode=='fydeptid'||item.attrcode=='fydeptid_v'){
        //费用承担部门
        // item.refcode='uapbd/refer/org/DeptTreeRef/index'
        item.queryCondition = ()=>{
            //let data = dataValues['fydwbm']==null?"":dataValues['fydwbm'].value;
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['fydwbm'].value))
            return {pk_org: data,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据apply_org过滤
        }
    }
    //收支项目
    if (item.attrcode == 'szxmid') {
       // item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/InoutBusiClassTreeRef.do";
        item.queryCondition = () => {            
            // let data = dataValues['fydwbm']==null?"":dataValues['fydwbm'].value;
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value;
            return {pk_org: data, TreeRefActionExt:PublicDefaultRefFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据assume_org过滤
        };
    }

    // 供应商
    if (item.attrcode == 'hbbm') {
        item.queryCondition = () => {
            let paytarget =  props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value
            if(paytarget!="1"){
                return {pk_org: ''};
            }
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value;
            return {pk_org:data, GridRefActionExt:SupplierTreeGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        };
    }
    // 供应商版本
    if (item.attrcode == 'hbbm_v') {
        item.queryCondition = () => {
            let paytarget =  props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value
            if(paytarget!="1"){
                return {pk_org: ''};
            }
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value;
            let date = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['djrq'].value
            return {pk_org:data, queryDate:date, GridRefActionExt:SupplierVersionGridRef, DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        };
    }

    //客户
    if (item.attrcode == 'customer') {
        item.queryCondition = () => {
            let paytarget = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value
            if(paytarget!="2"){
                return {pk_org: ''};
            }
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value
            return {pk_org: data, GridRefActionExt:CustomerTreeGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        };
    }
    //客户版本
    if (item.attrcode == 'customer_v') {
        item.queryCondition = () => {
            let paytarget = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value
            if(paytarget!="2"){
                return {pk_org: ''};
            }
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value
            let date = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['djrq'].value
            return {pk_org: data, queryDate:date, GridRefActionExt:CustomerVersionTreeGridRef ,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        };
    }
    if(item.attrcode=='receiver'){
        //收款人
        item.queryCondition = ()=>{
            let paytarget = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['paytarget'].value))
            if(paytarget!="0"){
                return {tradetype:window.presetVar.tradetype,pk_dept: '',GridRefActionExt:PsndocTreeFilterPath};
            }
            // let fydeptid = props.cardTable.getClickRowIndex(moudleid).record.values['fydeptid'].value
            // if(!fydeptid){
            //     fydeptid = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydeptid'].value
            // }
            let dwbm = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['dwbm'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['dwbm'].value))
            
            // return {pk_psndoc:filter[item.attrcode], pk_org: fydwbm, ExtRefSqlBuilder:''}; // 根据pk_org过滤
            return {pk_org:dwbm,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据assume_org过滤
            return {tradetype:window.presetVar.tradetype,GridRefActionExt:PsndocTreeFilterPath,pk_org:dwbm,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据assume_org过滤
        }
    }
    if(item.attrcode=='skyhzh'){
        //个人银行账户
        item.queryCondition = ()=>{
            let pk_org = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['fydwbm'].value))

            let receiver = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['receiver'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['receiver'].value))
            //银行账户参照代码没接受人员信息？先返回空
            return {pk_org, pk_psndoc:receiver,GridRefActionExt:PsnbankaccTreeGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    if(item.attrcode=='fkyhzh'){
        //单位银行账户
       // item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/BankaccDefaultGridRef.do";
        item.queryCondition = ()=>{
            let pk_org = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_payorg'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['pk_payorg'].value))
            let bzbm = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['bzbm'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['bzbm'].value))
            
            //银行账户参照代码没接受人员信息？先返回空
            return {pk_org:pk_org,pk_currtype:bzbm,GridRefActionExt:BankacctreeGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    //业务类型
    if(item.attrcode == 'busitype'){
        item.queryCondition = () => {
            let payOrg = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_payorg'].value;
            let tradeType = window.presetVar.tradetype
            let billType = '263X'
            return {payOrg:payOrg,tradeType:tradeType,billType:billType,GridRefActionExt:'nccloud.web.erm.action.ref.sqlbuilder.BusiTypeSqlBuilder',DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    if(item.attrcode=='cashproj'){
        //资金计划项目
        //item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/FundPlanTreeRef.do";
        item.queryCondition = ()=>{
            let pk_payorg = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_payorg'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['pk_payorg'].value))
            
            // let pk_group = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value; 
            
            return {pk_org:pk_payorg,/*isDisableDataShow:'N',*/DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        }
    }
    if(item.attrcode=='pk_cashaccount'){
        //现金账户
        //item.queryGridUrl=window.location.origin+"/nccloud/uapbd/sminfo/CashAccountGridRef.do";
        item.queryCondition = ()=>{
            let pk_payorg = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_payorg'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['pk_payorg'].value))
            
            let pk_group = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value;             
            return {pk_org: pk_payorg,pk_group:pk_group,TreeRefActionExt:'',DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        }
    }
    if(item.attrcode=='cashitem'){
        //现金流量项目
        //item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/CashflowTreeRef.do";
        item.queryCondition = ()=>{
            let pk_payorg = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_payorg'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['pk_payorg'].value))
            let pk_group = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value;                         
            return {pk_org: pk_payorg,pk_group:pk_group,TreeRefActionExt:'',DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        }
    }
    //会计科目单独判断,没有预制字段
    if (item.itemtype == 'refer' && item.refcode === 'uapbd/refer/fiacc/AccountDefaultGridTreeRef/index') {
        const config = {}
        item.queryCondition = (p) => {
            var pkAccountingbook = null;
            // const pk_org = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'pk_org')))
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value   //直接取表头pk_org
            try {
                ajax({
                    url: '/nccloud/erm/ref/queryAccountBookAction.do',
                    data: { pk_org },
                    async: false,
                    loading:false,
                    success: (res) => {
                        if (res.success) {
                            pkAccountingbook = res.data;
                        }
                    },
                    error:(err)=>{
                        console.log('queryAccountBookAction err', err);
                    }
                })
            } catch (error) {
                console.log('queryAccountBookAction error:', error);
            }

            config.TreeRefActionExt = 'nccloud.web.arap.ref.before.CrossRuleSqlBuilder';
            config.UsualGridRefActionExt = 'nccloud.web.arap.ref.before.CrossRuleSqlBuilder';
            config.itemKey = 'subjcode';
            config.pk_org = pk_org;
            config.pk_accountingbook = pkAccountingbook;
            const billdate = props.form.getFormItemsValue(presetVar.head.head1, 'billdate')
            config.dateStr = billdate &&  billdate.value ? (props.form.getFormItemsValue(presetVar.head.head1, 'billdate').value).substring(0,10) : null;
            config.DataPowerOperationCode = 'fi';//使用权组
            return config;
        }
    }
    if(item.attrcode=='freecust'){
        //散户
        item.queryCondition = ()=>{
            let paytarget = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['paytarget'].value))
            let customSupplier = '';
            if(paytarget=="0"){
                return {customSupplier:''};
            }else if(paytarget=="1"){
                // customSupplier = dataValues['hbbm']==null?"":dataValues['hbbm'].value;
                customSupplier = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['hbbm'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['hbbm'].value))
                
            }else if(paytarget=="2") {
                customSupplier = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['customer'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['customer'].value))
            }
           return {'pk_customsupplier':customSupplier,'customSupplier': customSupplier,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        }
    }
    if(item.attrcode=='jobid'){
        //项目
        item.queryCondition = ()=>{
            let pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_payorg'].value;
            
            //银行账户参照代码没接受人员信息？先返回空
            return {pk_org:pk_org,GridRefActionExt:ProjecTreetGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    // //币种
    if (item.attrcode == 'bzbm') {
        // item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/InoutBusiClassTreeRef.do";
        item.queryCondition = () => {
            return {TreeRefActionExt:CurrtypeRefSqlFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        };
    }
    // //人员
    if (item.attrcode == 'jkbxr') {
        item.queryCondition = () => {
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['dwbm'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['dwbm'].value))
            return {tradetype:window.presetVar.tradetype,pk_org:data,org_id:data,GridRefActionExt:PsndocTreeFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据assume_org过滤
            // return{};
        };
    }
    //借款事由
    if (item.attrcode == 'zy') {
        item.queryCondition = () => {
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['dwbm'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['dwbm'].value))
            return {pk_org: data,TreeRefActionExt:PsndocTreeFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据assume_org过滤
        };
    }
	if(item.attrcode=='custaccount'){
        //客商银行账号
        item.queryCondition = ()=>{
            let accclass = "";
            let pk_cust = "";
            let paytarget = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['paytarget'].value))            
            if(paytarget=="1"){
                //收款对象为供应商
                accclass = "3";
                pk_cust = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['hbbm'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['hbbm'].value))            
                
            } else if(paytarget=="2"){
                //收款对象为客户
                accclass = "1";
                pk_cust = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['customer'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['customer'].value))            
                
            }
            let bzbm = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['bzbm'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['bzbm'].value))            
            
            return { pk_cust: pk_cust,accclass:accclass,pk_currtype:bzbm,TreeRefActionExt:'',DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    if(item.attrcode=='pk_checkele'){
        //核算要素
        item.queryCondition = ()=>{
            let pk_org = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value) : (props.cardTable.getClickRowIndex(moudleid).record.values['pk_org'].value))            
            
            return {pk_org: pk_org,TreeRefActionExt:'',DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    if(item.attrcode=='pk_resacostcenter'){
        //成本中心
        item.queryCondition = ()=>{
            let pk_pcorg = ""
            let pk_group = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value
            let pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value 
            if(moudleid == presetVar.head.head1) {
                pk_pcorg = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_pcorg'].value
            } else  {
                pk_pcorg = getBodyValueBeforeRefRequest(props, moudleid, 'pk_pcorg')
            }         
            return { pk_org: pk_org,pk_group: pk_group,pk_profitcenter: pk_pcorg,TreeRefActionExt:PublicDefaultRefFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    // //合同号
    if (item.attrcode == 'fctno') {
        // item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/InoutBusiClassTreeRef.do";
        item.queryCondition = () => {
            let pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;           
            let bzbm = props.cardTable.getClickRowIndex(moudleid).record.values['bzbm'].value;         
            let hbbm = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['hbbm'].value;
            
            return {GridRefActionExt:PublicDefaultGridRef,pk_org:pk_org,corigcurrencyid:bzbm,cvendorid:hbbm,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        };
    }

    if (item.attrcode == 'jsfs') {
        //结算方式
        item.queryCondition = () => {
            return {GridRefActionExt:'nccloud.web.erm.action.ref.sqlbuilder.BalatypeSqlBuilder', DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};   
        }
    }

    let bodys = Object.values(window.presetVar.body);
    let bodyarr = [];
    bodys.forEach((one)=>{
            bodyarr[bodyarr.length] = one;
    })
    //处理交叉校验规则
    if (item.itemtype == 'refer') {
        let oldQueryCondition = item.queryCondition;
        let crossrule_itemkey = item.attrcode;
        item.queryCondition = (obj) => {
            let crossrule_datasout = props.createExtCardData(pageTo.getSearchParam("p"), "head", bodyarr);
            let crossrule_tradetype = props.form.getFormItemsValue(presetVar.head.head1,'djlxbm').value;
            let crossrule_org = ''
            // 利润中心
            if(item.attrcode=='pk_pcorg'){
                crossrule_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value
            } else {
                crossrule_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value
            }
            let crossrule_datatypes = 'extbillcard';
            let isHead = moudleid == presetVar.head.head1 ? "true" : "false"
          
            let crossrule_datas = crossrule_datasout;
            if(moudleid!='head' && window.presetVar.bodyChangeValuesAll!=null) {
                crossrule_datas.bodys[moudleid].rows = [window.presetVar.bodyChangeValuesAll];
            }
            let conditionFlag = true;
            if (oldQueryCondition == null || oldQueryCondition == undefined || oldQueryCondition == 'undefined') {
                conditionFlag = false;
            }

            let oldData = '';
            if (conditionFlag) {
                oldData = oldQueryCondition();
            }
            if (oldData == null || oldData == undefined || oldData == 'undefined') {
                oldData = '';
            }

            let config = { 
                crossrule_datas:JSON.stringify(crossrule_datas),
                crossrule_tradetype:crossrule_tradetype,
                crossrule_org:crossrule_org, 
                crossrule_datatypes:crossrule_datatypes,
                crossrule_area:moudleid,
                crossrule_itemkey:crossrule_itemkey,
                crossrule_isHead : isHead,
                ...oldData
                };

            //参照类型的自定义项字段增加组织过滤
            if (
                !oldData.pk_org &&
                obj &&
                obj.attrcode &&
                (obj.attrcode.startsWith('defitem') || obj.attrcode.startsWith('zyx') || obj.datatype == '56')
            ) {
                config.pk_org = crossrule_org;
            }

            if (obj == undefined || obj == null || obj.refType == undefined || obj.refType == null) {
                if (
                    config.TreeRefActionExt == null ||
                    config.TreeRefActionExt == undefined ||
                    config.TreeRefActionExt.length == 0
                ) {
                    config.TreeRefActionExt = PublicDefaultGridRef;
                }
                return config;
            }

            if (obj.refType == 'grid') {
                if (
                    config.GridRefActionExt == null ||
                    config.GridRefActionExt == undefined ||
                    config.GridRefActionExt.length == 0
                ) {
                    config.GridRefActionExt = PublicDefaultGridRef;
                }
            } else if (obj.refType == 'tree') {
                if (
                    config.TreeRefActionExt == null ||
                    config.TreeRefActionExt == undefined ||
                    config.TreeRefActionExt.length == 0
                ) {
                    config.TreeRefActionExt = PublicDefaultGridRef;
                }
            } else if (obj.refType == 'gridTree') {
                if (
                    config.GridRefActionExt == null ||
                    config.GridRefActionExt == undefined ||
                    config.GridRefActionExt.length == 0
                ) {
                    config.GridRefActionExt = PublicDefaultGridRef;
                }
            }

            return config;
        }
    }



}

function filterDatas(data){
    if(data==null){
        return {rows:[]}
    }
    let rows = data.rows;
    for(let i=0;i<rows.length;i++){
        if(rows[i].values==undefined){
            continue;
        }
        let values = rows[i].values;
        for(let item in values){
            if(item.indexOf('.')>-1&&values[item]!=undefined&&values[item]!=null){
            //    let itemp = item.substring(0,item.indexOf('.'));
               if(values[item].display==null||values[item].display==undefined||values[item].display==''){
                   values[item] = {value:null,display:null,scale:null};
               }else{
                  //元数据.属性不以参照形式显示直接显示名称.
                 values[item] = {value:values[item].display,display:values[item].display,scale:null};
               }
            }
        }
    }
    return data
}

/**
 * 表体参照请求前获取表体行某字段的值
 * @param {} props 
 */
 function getBodyValueBeforeRefRequest(props, tablecode, key){
    let clickRow = props.cardTable.getClickRowIndex(tablecode)
    if (clickRow){
        if(clickRow.record.values[key]) {
            return clickRow.record.values[key].value;
        } else {
            toast({content:`表体模板缺少配置项${key}`, color:'danger'})
            return null
        }
    }else{
        let currentIndex = props.cardTable.getCurrentIndex(tablecode);
        return props.cardTable.getDataByIndex(tablecode, currentIndex).values[key].value;
    }
    
}

export default  requestApiOverwrite;
